package memory;

import memory.SquareDisplayHandler;
import memory.Controller;
import java.applet.Applet.*;
import java.awt.event.*;
import javax.swing.Timer;
import memory.GUI.SquarePanel;

public class SquareListener extends MouseAdapter {

    SquarePanel s;
    Controller cont;
    Timer timer;


    public SquareListener(SquarePanel s, Controller cont) {
        super();
        this.cont = cont;
        this.s = s;
    }

    @Override
    public void mouseClicked(MouseEvent e) {
        if (cont.isFirstClick()) {
            cont.startTimer();
            cont.setFirstClick(false);
        }
        // click check, if the first of two then it will go to the else
        if (cont.getLastClicked() != null) {
            // we have a match - so do the below stuff
            if (!s.equals(cont.getLastClicked()) && s.getSquare().isMatch(cont.getLastClicked().getSquare())) {

                cont.playSound();
                s.displayImage();
                s.setMatched();
                cont.getLastClicked().setMatched();
                s.removeMouseListener(this);
                cont.getLastClicked().removeMouseListener(this);
                cont.setLastClicked(null);
                if (cont.isGameOver()) {
                    cont.gameOver();
                }
            } else if (s.equals(cont.getLastClicked())) {
                // Don't change anything
            }
            else {
                s.setClicked();
                s.displayImage();
                cont.enableGlassPane();
                timer = new Timer(500, new SquareDisplayHandler(cont, s, timer));
                timer.start();
                timer.setRepeats(false);
                cont.setLastClicked(null);
            }
        } else {
            cont.setLastClicked(s);
            cont.getLastClicked().setClicked();
            cont.getLastClicked().displayImage();
        }
    }
}
